<template>
    <div v-loading="isLoading">
        <div class="message-list">
            <div style="width: 160vh;" v-for="(message,index) in messages" :key="index">
                <div style="margin-top: 40px;text-align: left;width: 90vh;" v-if="message.system" >
                    <div style="float: left;"><img class="avatar" :src="address.minioUrl+'image/' + message.avatar" alt=""></div>
                    <div class="message" v-html="postProcessHtml(md.render(message.message))"></div>
                </div>
                <div v-else style="margin-top: 40px;text-align: right;">
                    <div style="float: right;"><img class="avatar" :src="address.minioUrl+'image/' + message.avatar" alt=""></div>
                    <div class="message" v-html="postProcessHtml(md.render(message.message))"></div>
                </div>
            </div>

        <!-- 有正在回答时的临时div -->
            <div v-if="answer.length>0" style="margin-top: 40px;text-align: left;width: 90vh;">
                <div style="float: left;"><img class="avatar" :src="address.minioUrl+'image/1.png'" alt=""></div>
                <div class="message" v-html="postProcessHtml(md.render(answer))"></div>
            </div>
        </div>


        <div class="message-input">
            <el-input :disabled="inputDisable" style="font-size: 16px;" type="textarea" rows="6" v-model="messageInput.message" placeholder="请输入消息" @keydown.enter.exact.prevent="enter()"     @keydown.shift.enter="()=>{}"></el-input>
        </div>

        <div style="text-align: center;margin-top: 15px;">
            <el-button style="height: 40px;" type="danger" plain @click="clearChat()" :disabled="inputDisable">清空聊天记录</el-button>
            <span style="margin-left: 30px;">模型选择：</span>
            <el-radio-group v-model="model">
                <el-radio value="deepseek-v3-671b" size="large">deepseek-v3 [业务问题选择我]</el-radio>
                <el-radio value="deepseek-r1-distill-qwen" size="large">deepseek-r1-深入思考</el-radio>
                <el-radio value="deepseek-r1-671b" size="large">deepseek-r1</el-radio>
            </el-radio-group>
        </div>
    </div>



</template>

<script setup lang="ts">
    import MarkdownIt from 'markdown-it'
    import request from '@/base/request'
    import { ref, onMounted, nextTick } from 'vue'
    import Message from '@/types/user/Message'
    import checkLogin from '@/utils/checkLogin'
    import router from '@/router'
    import { ElMessage } from 'element-plus'
    import { address } from '@/base/address'
    const inputDisable=ref(false)
    const messages = ref<Message[]>([])
    const isLoading = ref(false)
    const answer = ref<string>('')
    const model=ref<string>('deepseek-v3-671b')
    const md = new MarkdownIt({
        html: true,        // 启用HTML标签
        breaks: true,      // 转换换行符为 <br>
        linkify: true,      // 将URL文本转换为链接
    })


    const enter=async()=>{
        if(messageInput.value.message.length==0){
            ElMessage.error('请输入消息')
            return;
        }
        inputDisable.value=true;
        try{
            await sendMessage(messageInput.value);
            messageInput.value.message = '';
            await getAnswer()
        }finally{
            inputDisable.value=false;
        }   
    }


    const clearChat=async()=>{
        const response=(await request.get("/user/userBaseInfo/clearChat")).data
        if(response.code==200){
            ElMessage.success("清空成功")
            localStorage.removeItem('message');
            window.location.reload();
        }else{
            ElMessage.error(response.msg)
        }
        
        
    }


    const postProcessHtml = (html:string) => {
      return html.replace(/<\/think><\/p>/g, '</p></think>');  //html解析错误调整
    };
    const messageInput = ref<Message>({
        system:false,
        message:''
    })

    const getMessages = async () => {
        const response = (await request.get(`/user/userBaseInfo/getMessageList`)).data;
        messages.value = response.data;
        await scrollToBottom();
    }

    const scrollToBottom = async () => {
        await nextTick()
        const messageList = document.querySelector('.message-list')
        if (messageList) {
            messageList.scrollTop = messageList.scrollHeight
        }
    }

    const sendMessage = async (message:Message) => {
        const response = (await request.post(`/user/userBaseInfo/sendMessage`,message)).data;
        if(response.code == 200){
            messages.value.push(response.data);
            await scrollToBottom();
        }else{
            ElMessage.error(response.msg);
            throw new Error(response.msg);
        }

        localStorage.setItem('message',JSON.stringify(messages.value));
    }


    const getAnswer = async () => {
        answer.value='';
        //不断请求直到结束,把每次请求结果拼接到answer.value
        //结束之后调用sendMessage,保存答案消息
        // 最后将answer清空
        const response= await fetch(`/api/user/userBaseInfo/getAnswer/${model.value}`)
        if(!response.ok){
            ElMessage.error('获取答案失败')
            return;
        }
        const reader=response.body?.getReader();
        while(true){
            const {done,value}=await reader?.read();
            if(done){
                break;
            }
            
            answer.value+=new TextDecoder().decode(value,{stream:true})
            scrollToBottom()
        }
        if(answer.value==="" || answer.value.startsWith('{"code":500')){answer.value="服务器繁忙"}
        
        sendMessage({
            system:true,
            message:answer.value
        })
        answer.value='';
    }

    onMounted(async () => {
        isLoading.value = true;
        try{
            const isLogin = await checkLogin();
            if(!isLogin){
                router.push('/home/discover')
                ElMessage.error('请先登录')
                return;
            }
            const messageJson = localStorage.getItem('message');
            if(!messageJson){
                await getMessages();
            }else{
                messages.value = JSON.parse(messageJson);
            }
            const message:Message = {
                system:true,
                message:'你好，我是抖阳专属客服，有什么可以帮你的吗？'
            }
            sendMessage(message);
        }catch(error){
            console.log(error);
        }finally{
            isLoading.value = false;
        }
    })
</script>

<style scoped>





    .message-list{
        width: 100%;
        height: 60vh;
        overflow-y: auto;
        overflow-x: hidden;
    }
    .message-list::-webkit-scrollbar {
        display: none; 
    }

    .message-input{
        margin-top: 10px;
        width: 100%;
        background-color: rgb(18, 18, 18);
        
    }

    .message-input:hover{
        border-color: #2f2f2f;
    }

    .message-input:focus{
        border-color: #2f2f2f;
    }

    .message{
        user-select: text;
        margin-left: 50px;

    }

    .avatar{
        width: 40px;
        height: 40px;
        border-radius: 50%;
    }




</style>


<style>
    think{ 
        color: #959595;
        font-size: 13px;
        font-style: italic;
    }

</style>